<template>
  <view class="goodsDetail">
    <!-- 修改点：骨架屏显示条件基于数据加载状态 -->
    <page-skeleton :loading="showSkeleton" :type="2"></page-skeleton>

    <view
      v-if="
        !showSkeleton && goodsDetaile && Object.keys(goodsDetaile).length > 0
      "
    >
      <!-- 主图/navbar -->
      <view class="diagram">
        <view>
          <u-swiper
            height="838"
            :list="list"
            mode="number"
            imgMode="aspectFill"
            indicator-pos="bottomRight"
          ></u-swiper>
        </view>
      </view>
      <!-- 商品标语 -->
      <view class="card sloganBox">
        <view class="slogan_title">
          {{ goodsDetaile.name }}
        </view>
        <view class="slogan_numberBox">
          <view class="slogan_top">
            <view style="display: flex">
              <view class="slogan_number_price"
                ><text>￥</text>
                <text style="font-size: 48rpx">{{ displayPrice }} </text>
                <text v-if="availableTicket" class="oldPric"
                  >￥{{ goodsDetaile.money }}
                </text>
              </view>
            </view>
            <text class="slogan_number">已售{{ goodsDetaile.saleCount }}</text>
          </view>
          <!--  -->
          <view class="slogan_bottom" v-if="availableTicket">
            <text>{{ enumAll.SHOPMODEL[shopMode] }}</text>
            <text class="line">|</text>
            <view class="slogan_number_ticket">
              <text>抵扣{{ availableTicket }}元</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 服务 -->
      <view class="card serverBox" :class="{ serverBoxTop: availableTicket }">
        <view class="server">
          <text class="title">服务</text>
          <text>48小时内发货</text>
        </view>
        <view class="server">
          <text style="margin-left: 80rpx">下单两小时不可修改订单信息</text>
        </view>
        <!-- <view class="server" v-if="addressData">
          <text class="title">收货地址</text>
          <text>{{ addressData.addressStr }}</text>
        </view> -->
        <view class="server line">
          <view v-for="(item, index) in line" :key="index" class="lineItem">
            <image
              style="width: 38rpx; height: 32rpx; margin-right: 10rpx"
              :src="item.image"
              mode="scaleToFill"
            />
            <text class="title">{{ item.tilte }}</text>
          </view>
        </view>
      </view>
      <!-- 商品属性 -->
      <!-- <view class="card attribute">
      <view class="title">商品属性</view>
      <view class="content">
        <view class="content_title">分类:{{ categoryName }}</view>
        <view class="content_title">品牌:无</view>
        <view class="content_title">品牌:无</view>
        <view class="content_title">品牌:无</view>
      </view>
    </view> -->
      <!-- 商品详情 -->
      <view class="goods card">
        <view class="goods_title">商品详情</view>
        <view style="margin: 20rpx 0">分类:{{ categoryName }}</view>
        <view style="margin-bottom: 20rpx; font-size: 26rpx">{{
          goodsDetaile.name
        }}</view>
        <view class="goods_content">
          <u-image
            mode="widthFix"
            :src="image.resourceUrl"
            v-for="image in detaileList"
            :key="image.id"
          ></u-image>
        </view>
      </view>
      <!-- 底部购物栏 -->
      <view class="bottom_car">
        <bottomCar
          :addressData="addressData"
          :specs="specs"
          :shopProductSkus="shopProductSkus"
          :productObj="productObj"
          :goodsDetaile="goodsDetaile"
          ref="bottomCarRef"
        ></bottomCar>
      </view>
    </view>
    <NoPageComponent
      v-else-if="
        !showSkeleton &&
        (!goodsDetaile || Object.keys(goodsDetaile).length === 0)
      "
      :showButton="false"
      title="该商品已下架，请返回选择其他商品奥~"
    />
  </view>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
// 组件
import bottomCar from '@/packageG/components/bottomCar.vue'
import pageSkeleton from '@/components/hy-page-skeleton/index.vue'
import NoPageComponent from '@/components/hy-noPage/index.vue'
//api
import { productApi, enumAll, userApi, baseApi } from '@/api'
//存储
import { userGylCarStore } from '@/store'
// 图片
import zhiliang from '../../static/zhiliang.png'
import dian from '../../static/dian.png'

//初始化数据
const showSkeleton = ref(true) // 修改点：使用新的骨架屏显示状态
const params = reactive<any>({
  productId: '',
  shopId: 0,
  detail: true
})
const gylStore = userGylCarStore()
const specs = ref([]) //规格
const defaultAddressList = ref([])
const shopProductSkus = ref([]) //商品规格
const addressData = ref<any>({})
const productObj = ref<any>({
  image: '',
  price: '',
  highestScoreMoney: 0,
  availableTicket: 0
})

const list = ref([])
const detaileList = ref<any>([])
const goodsDetaile = ref<any>('')
const categoryName = ref<any>('')
const line = ref([
  { image: zhiliang, tilte: '官方质量保证' },
  { image: dian, tilte: '极速发货' }
])
const shopMode = ref()
// const buyParams = reactive({ lowestNum: 1, limitNum: 0, specialType: 0 })

//当前拥有的优惠
const discount = ref(computed(() => gylStore.discount))
//商品最高抵扣
const highestScoreMoney = ref(0)
// 获取子组件实例
const bottomCarRef = ref()

// 获取商品详情
const getProductDetail = async () => {
  try {
    const { data, code } = await productApi.getShopProductInfo(params)
    if (code == 200) {
      //轮播图
      list.value = data.skuResources.map((item: any) => {
        return {
          image: item.resourceUrl,
          title: item.remark
        }
      })
      // 最高抵扣
      highestScoreMoney.value = data.highestScoreMoney
      gylStore.setHighestScoreMoney(data.highestScoreMoney)
      // 详情图片
      detaileList.value = data.resources
      detaileList.value.unshift(data.bannerResources[0])
      // 商品数据
      goodsDetaile.value = data

      gylStore.money = data.money
      categoryName.value = data.category.name
      specs.value = data.specs

      productObj.value = {
        image: data.image,
        price: availableTicket.value > 0 ? displayPrice.value : data.money,
        highestScoreMoney: data.highestScoreMoney,
        availableTicket: availableTicket.value
      }

      shopProductSkus.value = data.shopProductSkus.map((item: any) => {
        return {
          ...item,
          lowestNum: item.lowestNum,
          specialType: item.specialType,
          limitNum: item.product.limitNum,
          count: item.count,
          shopProductSkuId: item.id,
          specs: item.specs,
          image: item.productSku.image,
          money: item.money,
          highestScoreMoney: item.highestScoreMoney,
          scoreMoney: discount.value
        }
      })

      //起购
      // buyParams.lowestNum = data.shopProductSkus[0].lowestNum
      // //国内0 海外购1 //需要增加身份证认证
      // buyParams.specialType = data.shopProductSkus[0].specialType
      // //限购
      // buyParams.limitNum = data.shopProductSkus[0].product.limitNum
    } else {
      list.value = []
      detaileList.value = []
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    list.value = []
    detaileList.value = []
    goodsDetaile.value = null
  }
}

// #region ***************** 优惠计算 ************************* /
// 计算当前可用的优惠券金额（从 Store 获取）
const availableTicket = computed(() => gylStore.availableTicket)
// 计算展示价格 (使用 Store 的计算方法)
const displayPrice = computed(() => gylStore.displayPrice)
// 获取优惠券信息
const getDiscountTicket = async () => {
  try {
    // 设置店铺模式到 Store
    gylStore.setShopMode(shopMode.value)

    // 从 Store 获取优惠券信息
    await gylStore.getDiscountTicket(shopMode.value)
  } catch (error) {
    uni.showToast({
      title: '获取优惠券失败',
      icon: 'none'
    })
  }
}

// #endregion

// 供应链商店id
const getGYL_SHOP_Id = (id: any) => {
  switch (Number(id)) {
    case 4:
      params.shopId = baseApi.advertising_enum.XFL_GYL_SHOP
      uni.setStorageSync('gylShopId', params.shopId)
      break
    case 6:
      params.shopId = baseApi.advertising_enum.CLKJ_GYL_SHOP
      uni.setStorageSync('gylShopId', params.shopId)
      break
    default:
      uni.showToast({ title: '请先清空软件，再进入', icon: 'error' })
      break
  }
}

onLoad(async (option) => {
  console.log('详情option', option)
  showSkeleton.value = true // 开始加载时显示骨架屏
  // 获取模式
  shopMode.value = uni.getStorageSync('shopMode')

  if (option?.mode) {
    shopMode.value = option.mode
  }
  if (option?.from) {
    uni.setStorageSync('isApp', option?.from)
  }
  // 区分模式获取折扣券
  getGYL_SHOP_Id(shopMode.value)
  await getDiscountTicket()
  if (option?.id) {
    params.productId = option.id
    await getProductDetail() // 等待接口调用完成
  } else {
    uni.showToast({
      title: '请选择商品',
      icon: 'none'
    })

    uni.navigateBack()
  }

  // 修改点：接口完成后再隐藏骨架屏
  showSkeleton.value = false
})
</script>
>

<style lang="scss" scoped>
.goodsDetail {
  padding-bottom: 100rpx;
  .diagram {
    height: 838rpx;
    .navbar {
      float: left;
    }
  }

  .sloganBox {
    position: absolute;
    top: 700rpx;
    width: 95%;
    border: 2rpx solid #e9313b;
    .slogan_title {
      font-size: 32rpx;
      line-height: 1.4; /* 设置行高 */
      max-height: 2.8em; /* 两行的高度 (line-height * 2) */
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2; /* 显示两行 */
      -webkit-box-orient: vertical;
      word-wrap: break-word;
      word-break: break-all;
    }
    .slogan_numberBox {
      margin-top: 20rpx;
      margin-left: -20rpx;
      margin-right: -20rpx;
      margin-bottom: -20rpx;
      padding: 10rpx;
      border-bottom-left-radius: 20rpx;
      border-bottom-right-radius: 20rpx;
      // background-color: #fff2ef;
      background-color: #e9313b;

      font-size: 26rpx;
      color: #fff;
      .slogan_number_price {
        font-weight: 700;
        .oldPric {
          font-size: 40rpx;
          margin-left: 20rpx;
          font-weight: normal;
          text-decoration: line-through;
        }
        .slogan_number_originalPrice {
          margin-left: 20rpx;
          color: #333;
          font-size: 30rpx;
          text-decoration: line-through;
          // font-style: italic; // 添加这行来实现斜体效果
        }
      }
      .slogan_top {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .slogan_bottom {
        display: inline-flex;
        align-items: center;
        padding: 5rpx 10rpx;
        color: #e9313b;
        border-radius: 10rpx;
        background-color: #fdcead;
        margin-top: 10rpx;
        font-size: 28rpx;

        .line {
          margin: 0 20rpx;
          color: #fff;
          font-weight: 700;
        }

        // 左侧文字
        text {
          text-align: center;
          color: #e9313b;
        }

        // 右侧优惠券区域
        .slogan_number_ticket {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          height: 50rpx;
          border-radius: 8rpx;

          // 优惠券文字
          text {
            font-weight: 700;
            color: #e9313b;
          }
        }
      }
    }
  }
  .serverBox {
    margin-top: 140rpx;
    .server {
      margin: 20rpx 0;
      .title {
        margin-right: 20rpx;
        color: #b2b2b2;
      }
    }
    .line {
      display: flex;
      align-items: center;
      .lineItem {
        display: flex;
        align-items: center;
      }
    }
  }

  .serverBoxTop {
    margin-top: 190rpx;
  }

  .attribute {
    margin-top: -10rpx;
    // margin-bottom: 10rpx;

    .title {
      font-size: 32rpx;
      // font-weight: 700;
      color: #333;
      margin-bottom: 20rpx;
    }
    .content {
      padding: 20rpx;
      border-radius: 20rpx;
      background: #f5f7fa;
      .title {
        font-size: 26rpx;
      }
    }
  }
  .goods {
    margin-top: -10rpx;
    .goods_title {
      margin-bottom: 20rpx;
      font-size: 32rpx;
    }
  }
  .bottom_car {
    width: 100%;
    position: fixed;
    bottom: 0;
    // padding: 20rpx;
  }
}

.card {
  padding: 20rpx;
  margin: 20rpx;

  border-radius: 20rpx;
  background-color: #fff;
}

:deep(.u-swiper-indicator) {
  bottom: 140rpx !important;
}
:deep(.u-navbar) {
  border-bottom: rgba(255, 255, 255, 0.5) !important;
  background: rgba(255, 255, 255, 0.5) !important;
}
</style>
